<template>
  <div>
    <!-- 头部 -->
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    />
    <!-- 搜索框 -->
    <van-search
      v-model.trim="keyword"
      placeholder="请输入搜索关键词"
      show-action
      shape="round"
      @input="suggest"
      @search="search(keyword)"
    >
      <template #action>
        <div @click="search(keyword)">搜索</div>
      </template>
    </van-search>
    <!-- 搜索建议 -->
    <van-cell-group v-if="sugList.length > 0">
      <van-cell
        icon="search"
        v-for="item in sugList"
        :key="item"
        @click="search(item)"
      >
        <template #title>
          <div v-html="highLight(item)"></div>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 搜索历史记录 -->
    <van-cell-group v-else>
      <van-cell title="历史记录"/>
      <van-cell @click="search(item)" :title="item" v-for="item in searchList" :key="item">
        <van-icon name="close" @click.stop="del(item)"/>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion } from '@/api/search'
import { getHistory, setHistory } from '@/utils/storage'
export default {
  name: 'search',
  data () {
    return {
      keyword: '',
      sugList: [],
      searchList: getHistory()
    }
  },
  methods: {
    suggest () {
      clearTimeout(this.timer)
      this.timer = setTimeout(async () => {
        if (this.keyword === '') {
          this.sugList = []
          return
        }
        const res = await getSuggestion(this.keyword)
        // console.log(res)
        this.sugList = res.data.options
      }, 500)
    },
    highLight (str) {
      return str.replace(new RegExp(this.keyword, 'gi'), match => {
        return `<span style="color: red;">${match}</span>`
      })
    },
    search (keyword) {
      // console.log('跳转')
      this.searchList = this.searchList.filter(item => item !== keyword)
      this.searchList.unshift(keyword)
      setHistory(this.searchList)
      this.$router.push({
        path: 'search/result',
        query: {
          keyword
        }
      })
    },
    del (key) {
      this.searchList = this.searchList.filter(item => item !== key)
      setHistory(this.searchList)
    }
  }
}
</script>

<style>

</style>
